package com.wanghengzhi.girlfriend.rbac.module.validator;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 王潇
 * @since 2021.4.8
 */
@RestControllerAdvice
public class ControllerValidatorAdvice {

    private static final String BAD_REQUEST_MSG = "客户端请求参数错误";
    /**
     * <1> 处理 form data方式调用接口校验失败抛出的异常
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return new ResponseEntity(collect, HttpStatus.BAD_REQUEST);
    }
    /**
     * <2> 处理 json 请求体调用接口校验失败抛出的异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<ObjectError> fieldErrors = e.getBindingResult().getAllErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return new ResponseEntity(collect, HttpStatus.BAD_REQUEST);
    }
    /**
     * <3> 处理单个参数校验失败抛出的异常
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity constraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect = constraintViolations.stream()
                .map(o -> o.getMessage())
                .collect(Collectors.toList());
        return new ResponseEntity(collect, HttpStatus.BAD_REQUEST);
    }

}
